<template>
	<section v-loading="listLoading">
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.title" clearable placeholder="标题"></el-input>
				</el-form-item>
				<el-form-item label="是否推荐" prop="recommend">
                    <el-select v-model="filters.recommend" clearable>
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="medium" v-on:click="handleCurrentChange(1)">查询</el-button>
				</el-form-item>
				<el-form-item class="fr">
				    <el-button type="primary" size="medium" plain @click="handleAdd">新增</el-button>
			    </el-form-item>
			</el-form>
		</el-col>
		<!--列表-->
		<el-table :data="users" stripe highlight-current-row @selection-change="selsChange" border style="width: 100%;">
			<el-table-column prop="id" label="ID" width="60" align="center">
			</el-table-column>
			<el-table-column prop="title" label="标题" min-width="80" align="center">
            </el-table-column>
            <el-table-column label="封面" min-width="80" align="center">
	           <template slot-scope="scope">
			      <el-popover placement="top-start" title="" trigger="click">
			        <img :src="scope.row.coverUrl" alt="" style="width: 500px;">
			        <img slot="reference" :src="scope.row.coverUrl" style="width: 40px;height: 40px;object-fit: cover;">
			      </el-popover>
			    </template>
	        </el-table-column>
			<el-table-column label="视频" width="80" align="center">
		        <template slot-scope="scope">
	                <el-button size="small" @click="handlePlay(scope.row)" v-if="scope.row.videoUrl" type="text">查看视频</el-button>
	                <span v-else>暂无视频</span>
	            </template>
		    </el-table-column>
		    <el-table-column prop="recommend" label="是否推荐" min-width="80" align="center">
		    	<template slot-scope="scope">
		    		<span>{{scope.row.recommend?'是' :'否'}}</span>
		    	</template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" min-width="80" align="center">
            </el-table-column>
			<el-table-column prop="addTime" label="创建时间" :formatter="formatDate"  width="150" align="center">
			</el-table-column>
			<el-table-column label="操作" width="150" align="center">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" plain size="mini" @click="handleDel(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination layout="prev, pager, next, jumper" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>
		
		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" width="800px" style="margin-top: -80px;"> 
			<el-form :model="addForm" label-width="80px"  ref="addForm">
				<el-form-item label="标题" prop="title" >
					<el-input  v-model="addForm.title" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="是否推荐" prop="recommend">
                    <el-select v-model="addForm.recommend" clearable>
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
				</el-form-item>
				<el-form-item label="排序" prop="sort" >
					<el-input  v-model="addForm.sort" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="视频">
					<div v-if="addForm.videoUrl" class="uploadVideo">
						<video :src="addForm.videoUrl" :poster="addForm.vodPhoto" controls style="width: 360px;height: 180px;"></video>
						<img class="uploadImgItemDel" @click="handleDelUrl(0)" src="http://blyw.oss-cn-hangzhou.aliyuncs.com/webStorage/web_1619754060794173.png"/>
					</div>
					<el-upload v-if="!addForm.videoUrl" action :http-request="Upload" :on-preview="handlePreview" :before-remove="beforeRemove" :on-remove="handleRemove" :on-success="handleSuccess" :on-exceed="handleExceed" drag :limit="limit" :file-list="fileList" >
				        <i class="el-icon-upload" ></i>
				        <div class="el-upload__text">
					                       将视频拖到此处，或
					        <em>点击上传</em>
				        </div>
			            <div slot="tip" class="el-upload__tip">上传文件大小不能超过 1G</div>
		            </el-upload>
		            <div v-if="addForm.url">上传文件大小不能超过 1G</div>
		            <el-progress v-show="showProgress" :text-inside="true" :stroke-width="15" :percentage="progress"></el-progress>
                </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="addFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="addSubmit">确定</el-button>
			</div>
		</el-dialog>
		
		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" width="800px" style="margin-top: -80px;"> 
			<el-form :model="editForm" label-width="80px"  ref="editForm">
				<el-form-item label="标题" prop="title" >
					<el-input  v-model="editForm.title" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="是否推荐" prop="recommend">
                    <el-select v-model="editForm.recommend" clearable>
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
				</el-form-item>
				<el-form-item label="排序" prop="sort" >
					<el-input  v-model="editForm.sort" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="视频">
					<div v-if="editForm.videoUrl" class="uploadVideo">
						<video :src="editForm.videoUrl" :poster="editForm.vodPhoto" controls style="width: 360px;height: 180px;"></video>
						<img class="uploadImgItemDel" @click="handleDelUrl(1)" src="http://blyw.oss-cn-hangzhou.aliyuncs.com/webStorage/web_1619754060794173.png"/>
					</div>
					<el-upload v-if="!editForm.videoUrl" action :http-request="UploadE" :on-preview="handlePreview" :before-remove="beforeRemove" :on-remove="handleRemove" :on-success="handleSuccess" :on-exceed="handleExceed" drag :limit="limit" :file-list="fileList">
				        <i class="el-icon-upload" ></i>
				        <div class="el-upload__text">
					                       将视频拖到此处，或
					        <em>点击上传</em>
				        </div>
			            <div slot="tip" class="el-upload__tip">上传文件大小不能超过 1G</div>
		            </el-upload>
		            <div v-if="editForm.videoUrl">上传文件大小不能超过 1G</div>
		            <el-progress v-show="showProgress" :text-inside="true" :stroke-width="15" :percentage="progress"></el-progress>
                </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="editFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="editSubmit">确定</el-button>
			</div>
		</el-dialog>
	    <!--播放视频界面-->
		<el-dialog title="视频" :visible.sync="playFormVisible" :close-on-click-modal="false" width="850px">
		  <video :src="data.videoUrl" :poster="data.coverUrl + '?x-oss-process=video/snapshot,t_10000,m_fast'" controls style="width: 800px;"></video>
		</el-dialog>
		
		
	</section>
</template>

<script>
	import { client,getFileNameUUID } from '../../common/js/alioss'
	import util from '../../common/js/util'
	export default {
		name: "Upload",
		props: {
			limit: {
				type: Number,
				default: 1
			}
		},
		data() {
			return {
				filters: {
					title: '',
					recommend:''
				},
				
				users: [],
				options:[{
					value:true,
					label:'是'
				},{
					value:false,
					label:'否'
				}],
				list:[],
				sels: [],
				fileList:[],
				total: 0,
				page: 1,
				pageSize: 10,
				listLoading: false,
		      ileList: [], //文件列
		      showProgress: false, //进度条的显示
		      dataObj: {}, //存签名信息
		      progress: 0, //进度条数据
		      data:{},
		      categoryList:[],
		      addLoading:false,
		      addFormVisible:false,
		      addForm:{
		      	coverUrl:'',
	      	    recommend:'',
	      	    sort:'',
	      	    videoUrl:'',
		      },
		      editLoading:false,
		      editFormVisible:false,
		      editForm:{
		      	title:'',
		      	coverUrl:'',
	      	    recommend:'',
	      	    sort:'',
	      	    videoUrl:'',
		      },
			  playFormVisible: false,
			  //进度条
			  isProgressVis: false,
			  percentage: 0,
			  fileLoading:false,
			}
		},
		methods: {
			
			//时间转换开始时间 
			formatDate(row, column) {
                let date = new Date(parseInt(row.addTime));
                let Y = date.getFullYear() + '-';
                let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) + '-' : date.getMonth() + 1 + '-';
                let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' ';
                let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
                let m = date.getMinutes()  < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
                let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                return Y + M + D + h + m + s;
            },
            dialogClose(){
                this.fileList = [];
            },
			
		    //添加图片
		    beforeAvatarUpload(file) {},//图片上传到阿里云
			// 文件超出个数限制时的钩子
			handleExceed(files, fileList) {
				this.$message.warning(`每次只能上传 ${this.limit} 个文件`);
			},
			// 点击文件列表中已上传的文件时的钩子
			handlePreview(file) {},
			// 删除文件之前的钩子
			beforeRemove(file, fileList) {
				return this.$confirm(`确定移除 ${file.name}？`);
			},
			// 文件列表移除文件时的钩子
			handleRemove(file, fileList) {},
			// 文件上传成功时的钩子
			handleSuccess(response, file, fileList) {
				this.fileList = fileList;
			},
			//文件上传前的校验
			beforeAvatarUploadV(file) {
				const isLt100M =
					file.size / 1024 / 1024 > 10 && file.size / 1024 / 1024 < 1024;
				const isLt30 = file.name.length < 30;
				if (["video/mp4"].indexOf(file.type) == -1) {
					this.$message.error("请上传正确的视频格式");
					return false;
				}
				if (!isLt100M) {
					this.$message.error("上传视频大小要在10MB~1GB之间哦!");
					return false;
				}
				if (!isLt30) {
					this.$message.error("上传视频文件名称长度必须要小于30个文字哦!");
					return false;
				}
			},
			// http-request属性来覆盖默认的上传行为（即action="url"），自定义上传的实现
			//multipartUpload方法查看官方文档[添加链接描述](https://www.alibabacloud.com/help/zh/doc-detail/31995.htm)
			Upload(file) {
				const that = this;
				async function multipartUpload() {
					let temporary = file.file.name.lastIndexOf(".");
					let fileNameLength = file.file.name.length;
					let fileFormat = file.file.name.substring(
						temporary + 1,
						fileNameLength
					);
					console.log(getFileNameUUID(),'getFileNameUUID()');
					console.log(fileFormat,'fileFormat');
					let fileName = getFileNameUUID() + "." + fileFormat;
					client(that.dataObj)
						.multipartUpload(`beizhi/${fileName}`, file.file, {
							progress: function(p) {
								//p进度条的值
								console.log(p);
								that.showProgress = true;
								that.progress = Math.floor(p * 100);
							}
						})
						.then(result => {
							//上传成功返回值，可针对项目需求写其他逻辑
							console.log(result,'上传成功了')
							var url = result.res.requestUrls[0]
							var index = url.lastIndexOf("?")
							url = url.substring(0, index)
							console.log(url,'新的链接')
							that.addForm.videoUrl = url;
		                    that.addForm.coverUrl = url + '?x-oss-process=video/snapshot,t_10000,m_fast';
//							let audioElement = new Audio(url);
//							audioElement.addEventListener("loadedmetadata", () => {
//							    that.addForm.duration = Math.floor(audioElement.duration); //时长为秒，小数，182.36
//							    console.log(that.addForm.duration,'duration');
//							});
						})
						.catch(err => {
							console.log("err:", err);
							console.log("上传失败了", err);
						});
				}
				multipartUpload();

			},
			UploadE(file) {
				const that = this;
				async function multipartUpload() {
					let temporary = file.file.name.lastIndexOf(".");
					let fileNameLength = file.file.name.length;
					let fileFormat = file.file.name.substring(
						temporary + 1,
						fileNameLength
					);
					console.log(getFileNameUUID(),'getFileNameUUID()');
					console.log(fileFormat,'fileFormat');
					let fileName = getFileNameUUID() + "." + fileFormat;
					client(that.dataObj)
						.multipartUpload(`beizhi/${fileName}`, file.file, {
							progress: function(p) {
								//p进度条的值
								console.log(p);
								that.showProgress = true;
								that.progress = Math.floor(p * 100);
							}
						})
						.then(result => {
							//上传成功返回值，可针对项目需求写其他逻辑
							console.log(result,'上传成功了')
							var url = result.res.requestUrls[0]
							var index = url.lastIndexOf("?")
							url = url.substring(0, index)
							console.log(url,'新的链接')
							that.editForm.videoUrl = url;
		                    that.editForm.coverUrl = url + '?x-oss-process=video/snapshot,t_10000,m_fast';
//							let audioElement = new Audio(url);
//							audioElement.addEventListener("loadedmetadata", () => {
//							    that.editForm.duration = Math.floor(audioElement.duration); //时长为秒，小数，182.36
//							    console.log(that.editForm.duration,'duration');
//							});
						})
						.catch(err => {
							console.log("err:", err);
							console.log("上传失败了", err);
						});
				}
				multipartUpload();

			},
			//删除视频
			handleDelUrl(index){
				if (index==0) {
					this.addForm.videoUrl = ''
				}else{
					this.editForm.videoUrl = ''
				}
				this.showProgress = false //进度条的显示
		        this.dataObj = {} //存签名信息
		        this.progress = 0 //进度条数据
			},
			//显示播放视频界面
			handlePlay: function (row) {
			    console.log(row)
			    this.playFormVisible = true;
			    this.data = row
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getUsers();
			},
			//获取商品列表
			getUsers:function (){
				this.listLoading = true;
				let para = {
					page: this.page,
					size: this.pageSize,
					title: this.filters.title,
					recommend: this.filters.recommend,
				};
				var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
				});  
				instance.post('admin/platform/manage/getVideoList', this.qs.stringify(para)).then(data => {
					let  res = data.data;
					console.log(data);
					if (res.code !== 0) {
						this.$message({
							message: res.msg,
							type: 'error'
						});
					} else {
						this.total = res.total;
						this.users = res.rows;
						this.listLoading = false;
					}
				});
			},
			//显示新增界面
			handleAdd: function () {
				this.showProgress = false //进度条的显示
		        this.dataObj = {} //存签名信息
		        this.progress = 0 //进度条数据
				this.addFormVisible = true;
				this.addForm = {
			      	sort:'',
			      	title:'',
			      	coverUrl:'',
		      	    recommend:'',
		      	    videoUrl:'',
				};
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确定新增吗?', '提示', {}).then(() => {
							this.addLoading = true;
                            let para = {
								sort:this.addForm.sort,
				            	title:this.addForm.title,
				            	coverUrl:this.addForm.coverUrl,
				            	recommend:this.addForm.recommend,
				            	videoUrl:this.addForm.videoUrl,
                            };
                            var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
							});  
							instance.post('admin/platform/manage/addVideo', this.qs.stringify(para)).then(data => {
								let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,  
										type: 'error'
									});
								} else {
									this.addLoading = false;
									this.$message({
										message:'成功',
										type: 'success'
									});
									this.$refs['addForm'].resetFields();
									this.addFormVisible = false;
									this.getUsers();
								}
							});
						});
					}
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.showProgress = false //进度条的显示
		        this.dataObj = {} //存签名信息
		        this.progress = 0 //进度条数据
				this.editFormVisible = true
				this.editForm.id = row.id
				this.editForm.title = row.title
				this.editForm.sort = row.sort
				this.editForm.recommend = row.recommend
				this.editForm.coverUrl = row.coverUrl
				this.editForm.videoUrl = row.videoUrl
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确定修改吗?', '提示', {}).then(() => {
							this.editLoading = true;
							let para = {
								id:this.editForm.id,
				            	coverUrl:this.editForm.coverUrl,
				            	recommend:this.editForm.recommend,
				            	sort:this.editForm.sort,
				            	title:this.editForm.title,
				            	videoUrl:this.editForm.videoUrl,
							}
							
							var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
							});  
							instance.post('admin/platform/manage/updVideo', this.qs.stringify(para)).then(data => {
								
								let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,
										type: 'error'
									});
								} else {
									this.editLoading = false;
									this.$message({
										message: '成功',
										type: 'success'
									});
									this.$refs['editForm'].resetFields();
									this.editFormVisible = false;
									this.getUsers();
								}
							});
						});
					}
				});
			},
			
			
			
			selsChange: function (sels) {
				this.sels = sels;
			},
			//删除
			handleDel(id) {
				this.$confirm('确定删除吗?', '提示', {}).then(() => {
					this.listLoading = true;
					var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
					});  
					instance.post('admin/platform/manage/delVideo', this.qs.stringify({id: id})).then(data => {
						
						let  res = data.data;
						if (res.code !== 0) {
							this.$message({
								message: res.msg,
								type: 'error'
							});
						} else {
							this.$message({
								message: '成功',
								type: 'success'
							});
							this.getUsers();
						}
					})
				}).catch(() => {

				});
			},
		},
		mounted() {
			this.getUsers();
		}
	}

</script>
<style>
	.advice{
		margin-left: 80px;
		margin-bottom: 10px;
		font-size: 12px;
	}
	.advice1{
		margin-left: 100px;
		margin-bottom: 10px;
		font-size: 12px;
	}
	.uploadImg{
  	    display: flex;
       	flex-direction: row;
  	    flex-wrap: wrap;
    }
    .uploadImgItem{
	  	display: flex;
	  	flex-direction: row;
	  	flex-wrap: wrap;
	  	margin-right: 10px;
	  	margin-bottom: 10px;
	  	width: 145px;
	  	height: 145px;
	  	position: relative;
    }
    .uploadImgItemDel{
	  	position: absolute;
	  	top: -5px;
	  	right: -5px;
	  	width: 30px;
	  	height: 30px;
    }
  
    .uploadVideo{
    	width: 360px;
    	height: 180px;
    	position: relative;
    }
</style>
